package edu.cn.nlsde.Utils;

import java.util.HashMap;

/**
 * Created by dell on 2016/5/21.
 */
public class SparseIntMatrix {
    private int row_num;
    private int column_num;
    private HashMap<Integer, HashMap<Integer, Integer>> store = new HashMap<>();

    public SparseIntMatrix() {

    }

    public SparseIntMatrix(int row, int column) {
        this.row_num = row;
        this.column_num = column;
    }

    public int get_row_num() {
        return row_num;
    }

    public int get_column_num() {
        return column_num;
    }

    public void set(int row, int column, Integer value) {
        HashMap<Integer, Integer> row_list = store.get(row);
        if (row_list == null) {
            row_list = new HashMap<>();
            store.put(row, row_list);
        }
        if (value != 0) {
            row_list.put(column, value);
        } else {
            row_list.remove(column);
        }
    }

    public void add(int row, int column, Integer value) {
        HashMap<Integer, Integer> row_list = store.get(row);
        if (row_list == null) {
            row_list = new HashMap<>();
            store.put(row, row_list);
        }
        if (value != 0) {
            Integer old_value = row_list.get(column);
            if (old_value == null) {
                row_list.put(column, value);
            } else {
                row_list.put(column, old_value + value);
            }

        }
    }

    public Integer get(int row, int column) {
        HashMap<Integer, Integer> tmp = store.get(row);
        if (tmp == null) {
            return 0;
        }
        Integer value = tmp.get(column);
        if (value == null) {
            return 0;
        }
        return value.intValue();
    }

    public void clear() {
        for (int row : store.keySet()) {
            store.get(row).clear();
        }
        store.clear();
    }

}
